import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:medito/constants/constants.dart';
import 'package:medito/widgets/network_image_widget.dart';
import 'package:flutter/material.dart';

class PackCardWidget extends StatefulWidget {
  const PackCardWidget({
    super.key,
    required this.title,
    this.subTitle,
    this.coverUrlPath,
    this.onTap,
  });

  final String title;
  final String? subTitle;
  final String? coverUrlPath;
  final void Function()? onTap;

  @override
  State<PackCardWidget> createState() => _PackCardWidgetState();
}

class _PackCardWidgetState extends State<PackCardWidget> {
  Future<ColorScheme?>? _colorSchemeFuture;

  @override
  void initState() {
    super.initState();
    _colorSchemeFuture = _generateColorScheme(context);
  }

  @override
  void didUpdateWidget(covariant PackCardWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.coverUrlPath != widget.coverUrlPath) {
      _colorSchemeFuture = _generateColorScheme(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    var textTheme = Theme.of(context).textTheme;

    return FutureBuilder<ColorScheme?>(
      future: _colorSchemeFuture,
      builder: (context, snapshot) {
        var colorScheme = snapshot.data;
        var backgroundColor =
            colorScheme?.primaryContainer ?? ColorConstants.onyx;
        var titleColor = colorScheme?.onPrimaryContainer ?? Colors.white;
        var subtitleColor = colorScheme?.onPrimaryContainer ?? Colors.white;

        return Container(
          decoration: BoxDecoration(
            color: backgroundColor,
            borderRadius: BorderRadius.circular(14),
          ),
          child: InkWell(
            onTap: widget.onTap,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (widget.coverUrlPath != null &&
                    widget.coverUrlPath!.isNotEmpty)
                  _getCoverUrl(),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _title(textTheme,
                            title: widget.title, color: titleColor),
                        if (widget.subTitle != null) const SizedBox(height: 4),
                        Expanded(
                          child: _description(
                            textTheme,
                            subtitle: widget.subTitle,
                            color: subtitleColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<ColorScheme?> _generateColorScheme(BuildContext context) async {
    if (widget.coverUrlPath != null && widget.coverUrlPath!.isNotEmpty) {
      // Skip processing images from dead domains
      if (HTTPConstants.isDeadDomain(widget.coverUrlPath!)) {
        return null;
      }

      try {
        var image = CachedNetworkImageProvider(widget.coverUrlPath!);

        return await ColorScheme.fromImageProvider(
          provider: image,
          brightness: Brightness.dark,
          contrastLevel: 1,
        ).timeout(const Duration(seconds: 5), onTimeout: () {
          throw TimeoutException('ColorScheme generation timed out');
        });
      } catch (e) {
        // Silently handle image loading errors for color scheme generation
        // This prevents crashes when pack cover images are missing or fail to load
        return null;
      }
    }
    return null;
  }

  Text _title(
    TextTheme textTheme, {
    required String title,
    required Color color,
  }) {
    return Text(
      title,
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      style: textTheme.displayLarge?.copyWith(
        fontFamily: dmSans,
        height: 1.2,
        color: color,
      ),
    );
  }

  Widget _description(
    TextTheme textTheme, {
    String? subtitle,
    required Color color,
  }) {
    if (subtitle != null) {
      return Text(
        subtitle,
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
        style: textTheme.titleMedium?.copyWith(
          letterSpacing: 0,
          color: color,
          fontSize: 14,
          height: 1.4,
        ),
      );
    }

    return const SizedBox();
  }

  Widget _getCoverUrl() {
    return ClipRRect(
      borderRadius: const BorderRadius.only(
        topLeft: Radius.circular(14),
        topRight: Radius.circular(14),
      ),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: NetworkImageWidget(
          url: widget.coverUrlPath ?? '',
          shouldCache: true,
        ),
      ),
    );
  }
}
